<?php
	$HTML_TITLE = "Agregar categorias";
	
	require_once("../php/db_settings.php");
	require_once("../php/db_functions.php");
	require_once("../php/db_noto.php");
	require_once("subcategory_validate.php");

	define("CONTEXT", "subcategory_list.php");
	
	$categories = get_categories();
	if(isset($_POST['subcategory_id'])) $_GET['id'] = $_POST['subcategory_id']; //esto es para cuando vengo del form
	$subcategory = get_subcategory($_GET['id']);
	$subcategory = $subcategory[0]; //como me devuelve un array piso con la primer posicion
		
	$languages = get_languages();
		
	if( $_SERVER[ 'REQUEST_METHOD'] == "POST" && validate() ){
						
		//update del padre
		$query = "UPDATE subcategory SET 
		category_id = '$_POST[category]' 
		WHERE subcategory.id = '$subcategory[id]'";
		$update = do_query($query);
		if(!$update) die($SQL_DATA['error']);
		
		//update en castellano
		$query = "UPDATE subcat_lang SET 
		description = '$_POST[subcategory_name_1]' 
		WHERE subcat_lang.subcategory_id = '$subcategory[id]' 
		AND subcat_lang.language_id = '1' ";
		$update = do_query($query);
		if(!$update) die($SQL_DATA['error']);
			
		//update en ingles
		$query = "UPDATE subcat_lang SET 
		description = '$_POST[subcategory_name_2]' 
		WHERE subcat_lang.subcategory_id = '$subcategory[id]' 
		AND subcat_lang.language_id = '2' ";
		$update = do_query($query);
		if(!$update) die($SQL_DATA['error']);
			
		header('Location: subcategory_list.php');
				
	} else {
		
		require_once("header.php");
		
		$subcat_data['category'] = $subcategory['category_id'];
		foreach($languages as $language){
			
			$queryDescription = "SELECT sc.id, scl.description
FROM subcategory as sc, subcat_lang as scl, language as l
WHERE sc.id = scl.subcategory_id
AND scl.language_id = '$language[id]'
AND sc.id = '$subcategory[id]'
AND l.id = '$language[id]' ";
			$subcat_lang = do_query($queryDescription);
			$subcat_lang = $subcat_lang[0];
			
			$subcat_data['subcategory_name_'.$language['id']] = $subcat_lang['description'];
			
		}
								
		include('subcategory_form.php');
		
		require_once("footer.php");	
	}	
?>